package net.apexes.wsonrpc.demo.server;

import net.apexes.wsonrpc.core.WsonrpcConfig;
import net.apexes.wsonrpc.server.PathAcceptors;
import net.apexes.wsonrpc.server.WsonrpcServer;
import net.apexes.wsonrpc.server.nano.NanoWsonrpcServer;
import net.apexes.wsonrpc.server.nano.http.threading.CachedThreadPoolAsyncRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author hedyn
 */
public class NanoDemoWsonrpcServerImpl extends AbstractDemoWsonrpcServer {

    private static final Logger LOG = LoggerFactory.getLogger(NanoDemoWsonrpcServerImpl.class);

    private NanoWsonrpcServer server;

    @Override
    public WsonrpcServer create(int port, String path, WsonrpcConfig config) {
        server = new NanoWsonrpcServer(port, PathAcceptors.startWithPath(path), config);
        server.setAsyncRunner(new CachedThreadPoolAsyncRunner(NamedThreadFactory.pool("wsd-")));
        server.setPingListener((sessionId, bytes) -> LOG.info("onPing: sessionId={}, length={}", sessionId, bytes.length));
        return server.getWsonrpcServer();
    }

    @Override
    public void startup() throws IOException {
        LOG.info("Startup...");
        server.start();
    }

    @Override
    public void shutdown() {
        if (server != null) {
            try {
                server.stop();
            } catch (Exception e) {
                LOG.error("", e);
            }
            server = null;
        }
    }
}
